package server;

import game.server.Game;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import server.utils.Configurations;
import server.utils.Log;

public class Server {
	
	public static Log log = new Log("log.txt", "conf.txt");
	public static Configurations conf;
	
	public static void main(String[] args) throws IOException {
		try {
			conf = new Configurations(log.readConf());
		} catch (Exception e1) {
			log.println("Insufficient configurations! Server ended!", true);
			System.exit(1);
		}
		ActiveSessions activeSessions = new ActiveSessions();
		OutboundMessages outMessages = new OutboundMessages();
		OutboundMessages inMessages = new OutboundMessages();
		ServerSocket serv;
		try {
			serv = new ServerSocket(conf.getPort());
			log.println("Server started...", conf.isConsole());
		} catch (Exception e) {
			log.println("Port unavailable!", conf.isConsole());
			return;
		}
		
		new Broadcaster(activeSessions, outMessages); //start();
		Game game = new Game(activeSessions, outMessages, inMessages); //start();
		try {
			while (true) {
				Socket sock = serv.accept(); 				// blocked!
				try {
					new ClientSession(sock, activeSessions, outMessages, 
							inMessages, game); //start()
				} catch (IOException e) {
					log.println("Socket creation error!", conf.isConsole());
					sock.close();
				}
			} 

		} finally {
			log.println("Server ended", conf.isConsole());
			serv.close();
		}
	}
}
